package com.hyz.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyz.reggie.common.RedisKeys;
import com.hyz.reggie.dao.UserDao;
import com.hyz.reggie.dto.LoginDto;
import com.hyz.reggie.pojo.User;
import com.hyz.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;
    @Override
    public boolean login(LoginDto loginDto) {
        if (loginDto == null) {
            return false;
        }
        Integer code = (Integer) redisTemplate.opsForValue().get(RedisKeys.RG_CODE+loginDto.getPhone());
        if (code == null) {
            return false;
        }
        if (!code.equals(loginDto.getCode())) {
            return false;
        }
        LambdaQueryWrapper<User> qwq = new LambdaQueryWrapper<>();
        qwq.eq(User::getPhone, loginDto.getPhone());
        User user = getOne(qwq);
        if (user == null) {
            user = new User();
            user.setPhone(loginDto.getPhone());
            save(user);
        }
       redisTemplate.delete(RedisKeys.RG_CODE+loginDto.getPhone());
        request.getSession().setAttribute("user",user.getId());
        return true;
    }

    @Override
    public void loginOut() {
        request.getSession().setAttribute("user",null);
    }
}
